package jupitermouse.site.sink.office.es;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch.util.RetryRejectedExecutionFailureHandler;
import org.apache.flink.streaming.connectors.elasticsearch6.ElasticsearchSink;
import org.apache.flink.util.Collector;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import static org.apache.kafka.common.requests.DeleteAclsResponse.log;

public class ESSinkApp {

    public static void main(String[] args) throws Exception {

        //获取参数
        int port = 9999;
        try{
            ParameterTool tool = ParameterTool.fromArgs(args);
            port = tool.getInt("port");
        }catch (Exception e){
            log.info("参数未设置，默认为9999");
        }

        //获取环境
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //读取数据
        DataStreamSource<String> source = env.socketTextStream("localhost", port);

        //转换操作
        SingleOutputStreamOperator<Tuple2<String, Long>> operator = source.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] values = value.toLowerCase().split(" ");
                Stream.of(values)
                        .forEach(item -> {
                            collector.collect(new Tuple2<>(item, 1L));
                        });
            }
        }).keyBy(0)
                .timeWindow(Time.seconds(5))
                .sum(1);
        operator.print().setParallelism(1);
        operator.addSink(sink2ES());

        env.execute("StreamingWCJavaApp");

    }
    /**
     * 写入ES
     * @return
     */
    private static ElasticsearchSink<Tuple2<String, Long>> sink2ES(){
        List<HttpHost> esHttphost = new ArrayList<>();
        esHttphost.add(new HttpHost("192.168.81.130", 9200, "http"));
        ElasticsearchSink.Builder<Tuple2<String, Long>> esSinkBuilder = new ElasticsearchSink.Builder<>(esHttphost,
                new ElasticsearchSinkFunction<Tuple2<String, Long>>() {
                    public IndexRequest createIndexRequest(Tuple2<String, Long> element) {
                        Map<String, String> map = new HashMap<>();
                        map.put("word", element.f0);
                        map.put("count", element.f1.toString());
                        return Requests.indexRequest()
                                .type("_doc")
                                .index("wd")
                                .source(map);
                    }

                    @Override
                    public void process(Tuple2<String, Long> element, RuntimeContext ctx, RequestIndexer indexer) {
                        indexer.add(createIndexRequest(element));
                    }
                }
        );
        esSinkBuilder.setBulkFlushMaxActions(1);
//        esSinkBuilder.setRestClientFactory(new RestClientFactoryImpl());
        esSinkBuilder.setFailureHandler(new RetryRejectedExecutionFailureHandler());
        return esSinkBuilder.build();
    }
}
